package com.song.druid.util;

import com.song.druid.annotation.SensitiveField;
import org.apache.commons.lang3.ObjectUtils;

import java.lang.reflect.Field;

public class SensitiveUtil {
    private final static String AES_KEY = "0abcdefggfedcba0";

    public static  <T> T encrypt(Field[] fields, T paramsObject) throws IllegalAccessException {
        for (Field field : fields) {
            SensitiveField sensitiveField = field.getAnnotation(SensitiveField.class);
            if (ObjectUtils.isNotEmpty(sensitiveField)){
                field.setAccessible(true);
                Object object = field.get(paramsObject);
                if (object instanceof String){
                    String value = (String) object;
                    String encrypt = AESUtil.encrypt(value, AES_KEY);
                    field.set(paramsObject, encrypt);
                }
            }
        }
        return paramsObject;
    }

    public static <T> T decrypt(Field[] fields, T paramsObject) throws IllegalAccessException {
        for (Field field : fields) {
            SensitiveField sensitiveField = field.getAnnotation(SensitiveField.class);
            if (ObjectUtils.isNotEmpty(sensitiveField)){
                field.setAccessible(true);
                Object object = field.get(paramsObject);
                if (object instanceof String){
                    String value = (String) object;
                    String decrypt = AESUtil.decrypt(value, AES_KEY);
                    field.set(paramsObject, decrypt);
                }
            }
        }
        return paramsObject;
    }

    public static <T> T decrypt(T result) throws IllegalAccessException {
        Class<?> resultClass = result.getClass();
        Field[] fields = resultClass.getDeclaredFields();
        for (Field field : fields) {
            SensitiveField sensitiveField = field.getAnnotation(SensitiveField.class);
            if (ObjectUtils.isNotEmpty(sensitiveField)){
                field.setAccessible(true);
                Object object = field.get(result);
                if (object instanceof String){
                    String value = (String) object;
                    String decrypt = AESUtil.decrypt(value, "0abcdefggfedcba0");
                    field.set(result, decrypt);
                }
            }
        }
        return result;
    }
}
